package org.example.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.dao.dto.log.EsLog;
import org.example.dao.dto.user.UserDto;
import org.example.dao.entity.user.UStudent;
import org.example.exception.ServerErrorException;
import org.example.skytool.commom.ContextUtil;
import org.example.skytool.date.TimeZoneUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author 22449
 */
@Component
@Aspect
@Slf4j
public class LogTraceProxy {


    @Resource
    ContextUtil contextUtil;

    @Resource
    TimeZoneUtil timeZoneUtil;

    @Around("@annotation(org.example.annotation.LogTrace)")
    public Object loopAccessMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        EsLog esLog = new EsLog();
        Long userId = contextUtil.getId();
        esLog.setUserId(userId.toString());
        Object target = joinPoint.getTarget();
        String className = target.getClass().getName();  //当前执行的方法所属的类、包
        esLog.setClassName(className);
        Method method = getMethod(joinPoint);
        Parameter[] parameters = method.getParameters();
        Object[] objs = joinPoint.getArgs();
        StringBuffer paramMsg = new StringBuffer();
        paramMsg.append("param:");
        for(int i = 0;i< parameters.length;i++){
            paramMsg.append(parameters[i].getName());
            paramMsg.append(",");
            paramMsg.append(objs[i]);
            paramMsg.append(";");
        }
        esLog.setParamMsg(paramMsg.toString());
        String methodName = method.getName();
        esLog.setMethodName(methodName);
        log.info(esLog.toString());
        return  joinPoint.proceed();
    }

    protected Method getMethod(ProceedingJoinPoint pjp) {
        Method method = null;
        try {
            MethodSignature ms = (MethodSignature) pjp.getSignature();
            method = pjp.getTarget()
                    .getClass()
                    .getMethod(ms.getName(), ms.getParameterTypes());
        } catch (NoSuchMethodException e) {
            throw new ServerErrorException("快快联系后端，大问题");
        }
        return method;
    }


}
